<?php

namespace App\Admin\Controllers\access;


use App\Admin\Controllers\access\actions\ExporterAccess;
use App\Admin\Controllers\access\actions\JumpAccessMember;
use App\Admin\Controllers\access\actions\JumpAccessVoteLeader;
use App\Admin\Controllers\access\actions\JumpEdit;
use App\Common\statement\CommonStatement;
use App\Exceptions\api\BaseException;
use App\Models\access\AccessVote;
use App\Models\access\AccessVoteLeader;
use App\Models\access\AccessVoteMember;
use App\Models\User;
use App\Models\user\Depart;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class AccessVoteController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '投票考核';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AccessVote());

        $grid->model()->latest();

        $grid->disableExport();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
//        $grid->exporter(new ExcelExpoter());


        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1 / 2, function ($filter) {
                $filter->equal('title', __('Title'));
                $filter->equal('status', __('Status'))->select(CommonStatement::votestatus);
            });


            $filter->column(1 / 2, function ($filter) {
                $filter->between('created_at', __('Created at'))->datetime();
            });

        });

        $grid->column('id', __('ID'));
        $grid->column('title', __('Title'));
        $grid->column('founder', __('Founder'));
        $grid->column('end_time', __('End Time'));
        $grid->column('status', __('Status'))->display(function ($status) {
            return CommonStatement::votestatus[$status];
        });
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->add(new JumpEdit());
            $actions->add(new JumpAccessVoteLeader());
            $actions->add(new JumpAccessMember());
            if ($actions->row->status == 2) {
                $actions->add(new ExporterAccess());
            }
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(AccessVote::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('cate_id', __('Cate'));
        $show->field('type', __('Type'));
        $show->field('title', __('Title'));
        $show->field('content', __('Content'))->editor();
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new AccessVote());

        $form->column(1/3, function ($form) {
            $form->text('id', __('ID'))->readonly();
            $form->text('title', __('Title'))->required();
            $form->text('founder', __('Founder'))->required();
            $form->datetime('end_time', __('结束时间'))->required();
//            $form->number('best_rate', __('好评比率'))->default(0.40)->required();
            $form->number('score_level_best', __('好评得分'))->default(90)->required();
            $form->number('score_level_good', __('较好得分'))->default(80)->required();
            $form->number('score_level_general', __('一般得分'))->default(70)->required();
            $form->number('score_level_poor', __('较差得分'))->default(60)->required();
            $form->decimal('main_leader_rate', __('主要领导得分占比'))->default(0.40)->required();
            $form->decimal('direct_leader_rate', __('分管领导得分占比'))->default(0.40)->required();
            $form->decimal('other_leader_rate', __('其他领导得分占比'))->default(0.20)->required();
            $form->radio('status', __('Status'))->options(CommonStatement::votestatus)->default(1);
        });
        $form->column(2/3,function ($form){
            $form->checkboxCard('leader_id', __('分管领导'))->options(
                User::whereIn('level', [2])->pluck('name', 'id')
            );
            $form->hasMany('member', "选择被投票人",function (Form\NestedForm $form) {
                $form->select('user_id',__('被投票人'))->options(User::where('level', 1)->pluck('name', 'id'));
                $form->text('remark',__('评价'));
            });
            $form->editor('intro', __('规则描述'));
        });

//        $form->ignore(['main_leader_id','leader_id','vote_user_id']);
        $form->saving(function (Form $form) {
            $accessId = $form->model()->id;
//            if ($form->model()->status != 2 && $form->status == 2) {
//                $check = AccessVoteLeader::where('access_id', $accessId)->where('status', 0)->first();
//                if ($check) {
//                    return response()->json(['code' => 400, 'message' => '保存失败：还有领导未投票']);
//                }
//            }
            $main_leader_id = User::where('level', 3)->pluck('id')->toArray();
            $form->leader_id = array_merge($main_leader_id, $form->leader_id);
        });
        $form->saved(function (Form $form) {
            $direct_leader_id = [];
            $vote_user_id = AccessVoteMember::where('access_id',$form->model()->id)->pluck('user_id','id')->toArray();
            $vote_user_id = array_flip(array_flip($vote_user_id));
            foreach ($vote_user_id as $user_val) {
                if ($user_val) {
//                    AccessVoteMember::firstOrCreate([
//                        'user_id' => $user_val,
//                        'access_id' => $form->model()->id,
//                    ]);
                    $user = User::where('id', $user_val)->first();
                    $superiorId = Depart::getSuperiorId($user['depart_id']);
                    if (!in_array($superiorId, $direct_leader_id)) {
                        $direct_leader_id[] = $superiorId;
                    }
                }
            }
            AccessVoteMember::whereNotIn('id', array_keys($vote_user_id))
                ->where('access_id', $form->model()->id)->delete();
            $leader_id_arr = $form->leader_id;
            for ($i = 0; $i < count($direct_leader_id); $i++) {
                if (!in_array($direct_leader_id[$i], $leader_id_arr)) {
                    $leader_id_arr[] = $direct_leader_id[$i];
                }
            }
            $leader_id = [];
            foreach ($leader_id_arr as $leader_val) {
                if ($leader_val) {
                    $user = User::where('id',$leader_val)->first();
                    if($user['level'] == 3){
                        $leader_type = 1;
                    }
                    if($user['level'] == 2){
                        if(in_array($leader_val,$direct_leader_id)){
                            $leader_type = 2;
                        }else{
                            $leader_type = 3;
                        }
                    }
                    AccessVoteLeader::firstOrCreate([
                        'leader_id' => $leader_val,
                        'access_id' => $form->model()->id,
                        'leader_type' => $leader_type
                    ]);
                    $leader_id[] = $leader_val;
                }
            }
            AccessVote::where('id', $form->model()->id)
                ->update(['leader_id' => implode(',', $leader_id),'vote_user_id'=>implode(',',$vote_user_id)]);
            AccessVoteLeader::whereNotIn('leader_id', $leader_id)
                ->where('access_id', $form->model()->id)->delete();
        });
        return $form;
    }

    public function getOtherLeader(Request $request)
    {
        dd($request);
    }

    /**
     * 导出
     * @return mixed
     */
    public function exports()
    {


        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(app_path() . '/Admin/Extensions/Excel/access_vote_template.xls');
        dd($spreadsheet);

        $worksheet = $spreadsheet->getActiveSheet();

        $worksheet->getCell('A1')->setValue('John');
        $worksheet->getCell('A2')->setValue('Smith');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->save('write.xls');


        $cellData = [
            ['学号', '姓名', '成绩'],
            ['10001', 'AAAAA', '99'],
            ['10002', 'BBBBB', '92'],
            ['10003', 'CCCCC', '95'],
            ['10004', 'DDDDD', '89'],
            ['10005', 'EEEEE', '96'],
        ];
        Excel::create('平时考核', function ($excel) use ($cellData) {
            $excel->sheet('score', function ($sheet) use ($cellData) {
                $sheet->rows($cellData);
            });
        })->store('xls')->export('xls');

//        return Excel::download(new ExportAccess(), 'access_vote.xlsx');

    }
}
